package cn.com.utt.gateway.controller;

import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;



import cn.com.utt.common.util.ImageCode;
import cn.com.utt.common.util.LocaleMessageSourceUtil;
import cn.com.utt.common.util.Tips;
import cn.com.utt.common.vo.RestResult;


@RestController
@RequestMapping("v1")
public class CodeImageController {
	
	@Autowired
    private LocaleMessageSourceUtil messageSourceUtil;
	
	@RequestMapping(value = "images/getcode",method = { RequestMethod.GET })
	public String imagecode(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception {
		response.setContentType("image/jpeg");
		OutputStream os = response.getOutputStream();
	    Map<String,Object> map = ImageCode.getImageCode(60, 20, os);
	    System.out.println(map.get("strEnsure"));
	    session.setAttribute("imageCode", String.valueOf(map.get("strEnsure")).toLowerCase());
	    try {
	        ImageIO.write((BufferedImage) map.get("image"), "JPEG", os);
	    } catch (Exception e) {
	    	e.printStackTrace();
	        return "";
	    }
	    return null;
	}
	
	@RequestMapping(value = "images/checkcode",method = { RequestMethod.POST })
	public Map<String,Object> checkCode(HttpSession session,String imageCode){
		RestResult result = new RestResult();
		if(imageCode==null){
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.NoVerificationCode));
			return result.toJsonObject();
		}
		String capt=(String)session.getAttribute("imageCode");
		if(capt==null){
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.IncorrectVerificationCode));
		}else{
			if(capt.equalsIgnoreCase(imageCode)&&capt.length()==imageCode.length()){
				result.setErrorCode(0);
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.CorrectVerificationCode));
			}else{
				result.setErrorCode(1);
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.IncorrectVerificationCode));
			}
		}
		return result.toJsonObject();
	}
}
